﻿Imports HTLibrary
Imports TNCBAL
Imports TNCDAL

Public Class ucFileHBL

    Private _objFile As tblFile ' Thông tin File
    Private _objFileMBL As tblFileMBL ' Thông tin MBL
    Private _objHBL As tblHBL

    Private _objHBLController As New HBLController
    Private _objFileMBLController As New FileMBLController


    Private _ucFileHBLGridView As ucFileHBLGridView

    Public Sub New(ByVal obj As tblFile)
        InitializeComponent()
        TextBoxHelper.TextBox_InitUpperStringEvent(Me.Controls)
        'Lưu thông tin File
        _objFile = obj

        InitCommands()
    End Sub

    Private Sub ucFileHBL_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ReloadForm()
    End Sub

    ''' <summary>
    ''' Reload lại toàn bộ dữ liệu form
    ''' </summary>
    ''' <param name="obj"></param>
    ''' <remarks></remarks>
    Public Sub ReloadForm(Optional ByVal obj As tblFile = Nothing)
        If obj IsNot Nothing Then
            _objFile = obj
        End If

        If _objFile Is Nothing Then
            MessageBox.Show("Phải nhập thông tin File trước khi tạo HBL")
            Return
        End If

        InitFormData()

        _objFileMBL = _objFileMBLController.GetMBLByFile(_objFile.ID_File)
        'Nếu chưa khởi tạo usercontrol GridView
        If _ucFileHBLGridView Is Nothing Then
            InitHBLDataGridView()
        End If

        _ucFileHBLGridView.BindingDataGridView(_objFileMBL)
        'Nếu không tồn tại row nào
        If _ucFileHBLGridView.DataGridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, _ucFileHBLGridView.DataGridView.Rows.Count)

        If _ucFileHBLGridView.DataGridView.RowCount = 0 Then
            _ucCommands.btnAdd.PerformClick()
        End If

        '----------------thêm phần hiển thị phần in AN và DO------------------------
        If (_objFile.IsExport) Then
            btPrintBL.Visible = True
            btPrintAN.Visible = False
            btPrintDO.Visible = False
        Else
            btPrintBL.Visible = False
            btPrintAN.Visible = True
            btPrintDO.Visible = True
        End If
        '----------------het phan in AN và DO
    End Sub

    ''' <summary>
    ''' Xét trường hợp Consignee
    ''' 
    ''' </summary>
    ''' <param name="isMaster"></param>
    ''' <remarks></remarks>
    Private Sub LoadConsignee(ByVal isMaster As Boolean)
        ''Nếu là dùng Master Bill
        'If isMaster Then
        '    'Nếu là hàng xuất thì consigne là Forwarder
        '    If _objFile.IsExport Then
        '        CViewer.BindingComboBox_ForeignCompany(cmbConsignee, _objFile.IsExport)
        '        Try
        '            cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany
        '        Catch ex As Exception
        '            cmbConsignee.Text = ""
        '            cmbConsignee.SelectedIndex = -1
        '        End Try
        '    Else 'Nếu là hàng nhập thì consignee là cty TNC
        '        'Consignee là Company
        '        CViewer.BindingComboBox_Company(cmbConsignee, _objFile.IsExport)
        '        Try
        '            cmbConsignee.SelectedValue = _objFile.ID_Company
        '        Catch ex As Exception
        '            cmbConsignee.Text = ""
        '            cmbConsignee.SelectedIndex = -1
        '        End Try
        '    End If
        'Else 'Nếu là dùng House Bill
        '    'Nếu là hàng xuất thì consignee là ForeignCompany
        '    If _objFile.IsExport Then
        '        CViewer.BindingComboBox_ForeignCompany(cmbConsignee, _objFile.IsExport)
        '        Try
        '            cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany
        '        Catch ex As Exception
        '            cmbConsignee.Text = ""
        '            cmbConsignee.SelectedIndex = -1
        '        End Try
        '    Else 'Nếu là hàng nhập thì consignee là Company
        '        CViewer.BindingComboBox_Company(cmbConsignee, _objFile.IsExport)
        '        Try
        '            cmbConsignee.SelectedValue = _objFile.ID_Company
        '        Catch ex As Exception
        '            cmbConsignee.Text = ""
        '            cmbConsignee.SelectedIndex = -1
        '        End Try
        '    End If

        'End If


        'Nếu là hàng xuất
        If _objFile.IsExport Then
            If isMaster Then 'Nếu là dùng Master Bill theo hãng tàu consignee là ForeignCompany
                CViewer.BindingComboBox_Agent(cmbConsignee)
                Try
                    cmbConsignee.SelectedValue = _objFile.ID_Agent
                Catch ex As Exception
                    cmbConsignee.Text = ""
                    cmbConsignee.SelectedIndex = -1
                End Try
            Else 'Nếu là dùng House Bill consignee là Company
                'Consignee là Company
                CViewer.BindingComboBox_ForeignCompany(cmbConsignee, _objFile.IsExport)
                Try
                    cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany
                Catch ex As Exception
                    cmbConsignee.Text = ""
                    cmbConsignee.SelectedIndex = -1
                End Try
            End If
        Else 'Nếu là hàng nhập
            If isMaster Then 'Nếu là dùng Master Bill thì consignee chính là TNC
                'Thông tin của cty TNC
                cmbConsignee.Text = ""
                cmbConsignee.SelectedIndex = -1

            Else 'Nếu là House Bill thì consignee là cty TNC
                CViewer.BindingComboBox_Company(cmbConsignee, _objFile.IsExport)
                Try
                    cmbConsignee.SelectedValue = _objFile.ID_Company
                Catch ex As Exception
                    cmbConsignee.Text = ""
                    cmbConsignee.SelectedIndex = -1
                End Try


                'CViewer.BindingComboBox_Company(cmbConsignee, _objFile.IsExport)
                'Try
                '    cmbConsignee.SelectedValue = _objFile.ID_Company
                'Catch ex As Exception
                '    cmbConsignee.Text = ""
                '    cmbConsignee.SelectedIndex = -1
                'End Try
            End If

        End If
    End Sub

    ''' <summary>
    ''' Khởi tạo các dữ liệu mặc định của form
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitFormData()

        If _objFile.IsExport Then
            'Consignee là ForeignCompany
            CViewer.BindingComboBox_ForeignCompany(cmbConsignee, _objFile.IsExport)
            Try
                cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany
            Catch ex As Exception
                cmbConsignee.Text = ""
                cmbConsignee.SelectedIndex = -1
            End Try


            'Nếu là hàng xuất thì không quản lý số tiền và % VAT của tờ khai thuế
            txtAmount.Visible = False
            lblAmount.Visible = False
            txtVATPercent.Visible = False
            lblVAT.Visible = False
        Else
            'Consignee là Company
            CViewer.BindingComboBox_Company(cmbConsignee, _objFile.IsExport)
            Try
                cmbConsignee.SelectedValue = _objFile.ID_Company
            Catch ex As Exception
                cmbConsignee.Text = ""
                cmbConsignee.SelectedIndex = -1
            End Try

            chkIsCareOf.Visible = False
        End If
    End Sub

    ''' <summary>
    ''' Khởi tạo thông tin user control HBL datagridview
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitHBLDataGridView()
        _ucFileHBLGridView = New ucFileHBLGridView(_objFile.IsExport)
        'Event
        _ucFileHBLGridView.dataGridViewXHBL_CellDoubleClickEvent = New EventHandler(AddressOf dataGridViewXHBL_CellDoubleClickEvent)
        _ucFileHBLGridView.Dock = DockStyle.Fill
        _ucFileHBLGridView.dataGridViewXHBL_CurrentCellChangedEvent = New EventHandler(AddressOf dataGridViewXHBL_CurrentCellChanged)
        ExpandablePanelHBLList.Controls.Add(_ucFileHBLGridView)
        '_ucFileHBLGridView.FormatDataGridView()
    End Sub

    ''' <summary>
    ''' Reset giá trị trên form khi tạo mới
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub ResetControls()
        CViewer.ResetControls(Me.Controls)
        'Init obj
        _objHBL = New tblHBL

        'Thông tin của HBL
        'txtHBLNo.Text = ""
        txtGrossWeight.Text = "0"
        txtNetWeight.Text = "0"
        txtMeasurement.Text = "0"
        'txtGoodDescription.Text = ""
        'txtMarksNumbers.Text = ""
        'chkIsMaster.Checked = False
        'chkIsCareOf.Checked = False

        txtNotifyParty.Text = "SAME AS CONSIGNEE"

        'If _objFile.IsExport Then
        '    'Consignee là ForeignCompany
        '    Try
        '        cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany
        '    Catch ex As Exception
        '        cmbConsignee.SelectedIndex = -1
        '    End Try

        'Else
        '    Try
        '        'Consignee là Company
        '        cmbConsignee.SelectedValue = _objFile.ID_Company
        '    Catch ex As Exception
        '        cmbConsignee.SelectedIndex = -1
        '    End Try

        'End If
        'txtNotifyParty.Text = "SAME AS CONSIGNEE"

        InitTaxReturn()
    End Sub

    Private Sub InitTaxReturn()
        'Tax return
        txtTaxReturnNo.Text = ""
        txtAmount.Text = "0"
        txtVATPercent.Text = "0"
        dtCreatedDate.Value = Nothing
        dtExpiredDate.Value = Nothing
        txtTaxDescription.Text = ""
    End Sub

    Public Sub dataGridViewXHBL_CellDoubleClickEvent(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
        btnEdit_Click(Nothing, Nothing)
    End Sub

    ''' <summary>
    ''' Lấy thông tin HBL theo form nhập
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub GetInfoByForm()
        With _objHBL
            .IsMaster = chkIsMaster.Checked
            .ID_FileMBL = _objFileMBL.ID_FileMBL
            .HBLNo = txtHBLNo.Text
            .NotifyParty = txtNotifyParty.Text
            .GW = Double.Parse(txtGrossWeight.Text)
            .NW = Double.Parse(txtNetWeight.Text)
            .CBM = Double.Parse(txtMeasurement.Text)
            .GoodDescription = txtGoodDescription.Text
            .MarkNumber = txtMarksNumbers.Text


            If .tblTaxReturn Is Nothing Then
                .tblTaxReturn = New tblTaxReturn()
            End If

            'Chỉ lấy thông tin TaxReturn khi TaxReturn No. khác rỗng
            'If txtTaxReturnNo.Text <> String.Empty Then
            'Kiểm tra xem TaxReturn đã có chưa
            'Nếu chưa có thì khởi tạo

            'TaxReturn
            .tblTaxReturn.TaxReturnNo = txtTaxReturnNo.Text
            .tblTaxReturn.Amount = Double.Parse(txtAmount.Text)
            .tblTaxReturn.VATPercent = txtVATPercent.Text
            '.tblTaxReturn.CreatedDate = dtCreatedDate.Value
            Try
                'Nếu không phải ngày thì gán null
                If dtCreatedDate.Value = "#12:00:00 AM#" Then
                    .tblTaxReturn.CreatedDate = Nothing
                Else
                    .tblTaxReturn.CreatedDate = dtCreatedDate.Value
                End If
            Catch ex As Exception
                .tblTaxReturn.CreatedDate = Nothing
            End Try

            .tblTaxReturn.ExpiredDate = dtExpiredDate.Value
            Try
                'Nếu không phải ngày thì gán null
                If dtExpiredDate.Value = "#12:00:00 AM#" Then
                    .tblTaxReturn.ExpiredDate = Nothing
                Else
                    .tblTaxReturn.ExpiredDate = dtExpiredDate.Value
                End If
            Catch ex As Exception
                .tblTaxReturn.ExpiredDate = Nothing
            End Try
            .tblTaxReturn.Description = txtTaxDescription.Text
            'End If
        End With
    End Sub

#Region "Commands"
    'Private _ucCommands As ucCommands
    ''' <summary>
    ''' Init commands
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitCommands()
        '_ucCommands = New ucCommands(Me)
        '_ucCommands = New ucCommands()
        _ucCommands.InitControl(Me)
        _ucCommands.ShowHideButtons(True, True, True)
        _ucCommands.btnAddEvent_Click = New EventHandler(AddressOf btnAdd_Click)
        _ucCommands.btnEditEvent_Click = New EventHandler(AddressOf btnEdit_Click)
        _ucCommands.btnDeleteEvent_Click = New EventHandler(AddressOf btnDel_Click)
        _ucCommands.btnUpdateEvent_Click = New EventHandler(AddressOf btnUpdate_Click)
        _ucCommands.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel_Click)
        _ucCommands.Dock = DockStyle.Fill
        PanelExCommand.Controls.Add(_ucCommands)
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles btnAdd.Click
        ''EnableButtons(True)
        'If _ucFileMBLGridView.DataGridView.Rows.Count = 0 Then
        '    MessageBox.Show("Bạn phải tạo MBL trước khi tạo HBL")
        '    _ucCommands.btnCancel.PerformClick()
        '    Return
        'End If

        If _objFileMBL Is Nothing Then
            MessageBox.Show("Bạn phải tạo MBL trước khi tạo HBL")
            _ucCommands.btnCancel.PerformClick()
            Return
        End If

        txtHBLNo.Focus()
        ResetControls()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles btnEdit.Click
        'EnableButtons(True)
        If _ucFileHBLGridView.DataGridView.CurrentRow Is Nothing Then
            MessageBox.Show("Bạn chưa chọn HBL để sửa")
            _ucCommands.btnCancel.PerformClick()
            Return
        End If
        txtHBLNo.Focus()
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles btnDel.Click
        Try
            If MessageBox.Show(String.Format("Bạn thật sự muốn xóa HBLNo {0}?", _objHBL.HBLNo), "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                If _ucFileHBLGridView.DataGridView.CurrentRow Is Nothing Then
                    MessageBox.Show("Bạn chưa chọn HBL để xóa")
                    _ucCommands.btnCancel.PerformClick()
                    Return
                End If
                _objHBLController.Delete(_objHBL)
                'Reload datagridview
                _ucFileHBLGridView.BindingDataGridView(_objFile)
            End If
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles btnUpdate.Click
        'Kiểm tra tính hợp lệ của việc nhập dữ liệu ở FileMBL
        If Not Me.ValidateChildren(ValidationConstraints.Enabled) Then
            _ucCommands.EnableButtons(True)
            Exit Sub
        End If

        Try
            ErrorProvider1.Clear()
            'Lấy thông tin HBL theo form nhập
            GetInfoByForm()
            Dim action As enumAction
            Dim indexRow As Integer = -1
            If _ucFileHBLGridView.DataGridView.CurrentRow IsNot Nothing Then
                indexRow = _ucFileHBLGridView.DataGridView.CurrentRow.Index
            End If

            'Nếu tồn tại ID_HBL thì cập nhật
            If _objHBL.ID_HBL > 0 Then
                _objHBLController.Update(_objHBL)
                action = enumAction.Edit
            Else 'Không tồn tại thì thêm mới
                _objHBLController.Insert(_objHBL)
                action = enumAction.Add
                indexRow = _ucFileHBLGridView.DataGridView.Rows.Count
            End If
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(action, String.Format("HBL No {0} of File No {1}", _objHBL.HBLNo, _objFile.FileNo))

            'Refresh gridview
            _ucFileHBLGridView.BindingDataGridView(_objFileMBL, indexRow)
            'Set current row
            '_ucFileHBLGridView.DataGridView.Rows(indexRow).Selected = True
            'Refresh buttons
            'EnableButtons(False)

        Catch ex As Exception
#If DEBUG Then
            Throw ex
#Else
            MessageBox.Show(ex.Message)
#End If
        End Try

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles btnCancel.Click
        dataGridViewXHBL_CurrentCellChanged(Nothing, Nothing)
    End Sub
#End Region

    Private Sub dataGridViewXHBL_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            'Đang chỉnh sửa dữ liệu. Không chọn được.
            If _ucCommands.btnUpdate.Enabled Then
                Return
            End If

            If _ucFileHBLGridView.DataGridView.CurrentRow IsNot Nothing Then
                _objHBL = _objHBLController.SelectRecordById(_ucFileHBLGridView.DataGridView.CurrentRow.Cells("ID_HBL").Value) '_objFileMBLController.SelectRecordById(dataGridViewXHBL.CurrentRow.Cells("ID_FileMBL").Value)

                'Hiển thị thông tin HBL trên form
                'If _objHBL.IsMaster Then
                chkIsMaster.Checked = _objHBL.IsMaster
                'Else
                txtHBLNo.Text = _objHBL.HBLNo
                txtNotifyParty.Text = _objHBL.NotifyParty

                If _objHBL.GW IsNot Nothing Then
                    txtGrossWeight.Text = TextBoxHelper.TextBoxFormatNumber(_objHBL.GW.Value.ToString(), "#,##0.000")
                    'txtGrossWeight.Text = CollectionHelper.FormatQuantityStyle(_objHBL.GW.Value) 'String.Format("{0:#,0}", _objHBL.GW.Value) 'FormatNumber(_objHBL.GW.Value, 0, TriState.False)
                Else
                    txtGrossWeight.Text = "0"
                End If

                If _objHBL.NW IsNot Nothing Then
                    txtNetWeight.Text = TextBoxHelper.TextBoxFormatNumber(_objHBL.NW.Value.ToString(), "#,##0.000")
                    'txtNetWeight.Text = CollectionHelper.FormatQuantityStyle(_objHBL.NW.Value) 'String.Format("{0:#,0}", _objHBL.NW.Value) 'FormatNumber(_objHBL.NW.Value, 0, TriState.False)
                Else
                    txtNetWeight.Text = "0"
                End If

                If _objHBL.CBM IsNot Nothing Then
                    txtMeasurement.Text = TextBoxHelper.TextBoxFormatNumber(_objHBL.CBM.Value.ToString(), "#,##0.0000")
                    'txtMeasurement.Text = CollectionHelper.FormatQuantityStyle(_objHBL.CBM.Value) 'String.Format("{0:#,0}", _objHBL.NW.Value) 'FormatNumber(_objHBL.NW.Value, 0, TriState.False)
                Else
                    txtMeasurement.Text = "0"
                End If

                txtGoodDescription.Text = _objHBL.GoodDescription
                txtMarksNumbers.Text = _objHBL.MarkNumber


                'Hiển thị thông tin TaxReturn trên form
                If _objHBL.tblTaxReturn IsNot Nothing Then
                    With _objHBL.tblTaxReturn
                        txtTaxReturnNo.Text = .TaxReturnNo
                        Try
                            dtCreatedDate.Value = .CreatedDate
                        Catch ex As Exception
                            dtCreatedDate.Value = Nothing
                        End Try
                        Try
                            dtExpiredDate.Value = .ExpiredDate
                        Catch ex As Exception
                            dtExpiredDate.Value = Nothing
                        End Try
                        'dtCreatedDate.Value = IIf(.CreatedDate IsNot Nothing, .CreatedDate, "1/1/1900")
                        'dtExpiredDate.Value = IIf(.ExpiredDate IsNot Nothing, .ExpiredDate, "1/1/1900")
                        txtAmount.Text = CollectionHelper.FormatQuantityStyle(IIf(.Amount IsNot Nothing, .Amount, 0)) 'FormatNumber(IIf(.Amount IsNot Nothing, .Amount, 0), , TriState.False)
                        txtVATPercent.Text = IIf(.VATPercent IsNot Nothing, .VATPercent, 0)
                        txtTaxDescription.Text = .Description
                    End With
                Else
                    InitTaxReturn()
                End If
            Else
                ResetControls()
            End If
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub

    Private currentHBLNo As String

    Private Sub chkIsMaster_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkIsMaster.CheckedChanged
        chkIsCareOf.Enabled = chkIsMaster.Checked
        If chkIsMaster.Checked Then
            'LoadConsignee(True)
            currentHBLNo = txtHBLNo.Text
            txtHBLNo.Text = "MASTER" '_objFile.tblFileMBLs(0).tblMBL.MBLNo
        Else
            'LoadConsignee(False)
            'chkIsCareOf.Checked = False
            txtHBLNo.Text = currentHBLNo
            dataGridViewXHBL_CurrentCellChanged(Nothing, Nothing)
        End If
    End Sub

#Region "Thanh"
    Private Sub btPrintBL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrintBL.Click
        If (_objHBL IsNot Nothing) Then
            CViewer.PrintHBL(_objHBL.ID_HBL)
        End If
    End Sub
#End Region



    Private Sub btnCalculateSUM_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateSUM.Click
        'txtNetWeight.Text = CollectionHelper.FormatQuantityStyle(_objHBLController.CalculateSumNW(_objHBL.ID_HBL))
        'txtGrossWeight.Text = CollectionHelper.FormatQuantityStyle(_objHBLController.CalculateSumGW(_objHBL.ID_HBL))
        'txtMeasurement.Text = CollectionHelper.FormatQuantityStyle(_objHBLController.CalculateSumCBM(_objHBL.ID_HBL))

        txtNetWeight.Text = TextBoxHelper.TextBoxFormatNumber(_objHBLController.CalculateSumNW(_objHBL.ID_HBL).ToString(), "#,##0.000")
        txtGrossWeight.Text = TextBoxHelper.TextBoxFormatNumber(_objHBLController.CalculateSumGW(_objHBL.ID_HBL).ToString(), "#,##0.000")
        txtMeasurement.Text = TextBoxHelper.TextBoxFormatNumber(_objHBLController.CalculateSumCBM(_objHBL.ID_HBL).ToString(), "#,##0.0000")
    End Sub

#Region "Validating"

    Private Sub txtGrossWeight_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtGrossWeight.Validating
        Dim cancel As Boolean
        If String.IsNullOrEmpty(txtNetWeight.Text) Then
            cancel = True
            Me.ErrorProvider1.SetError(txtGrossWeight, "Chưa nhập trọng lượng GW!")
        Else
            Try
                Dim value As Double = Double.Parse(txtNetWeight.Text)
                If value < 0 Then
                    cancel = True
                    Me.ErrorProvider1.SetError(txtNetWeight, "Trọng lượng phải >= 0")
                End If
            Catch ex As Exception
                cancel = True
                Me.ErrorProvider1.SetError(txtNetWeight, "Trọng lượng này phải là giá trị số!")
            End Try
        End If

        If cancel = True Then
            txtGrossWeight.Focus()
        End If

        e.Cancel = cancel
    End Sub

    Private Sub txtNetWeight_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtNetWeight.Validating
        Dim cancel As Boolean
        If String.IsNullOrEmpty(txtNetWeight.Text) Then
            cancel = True
            Me.ErrorProvider1.SetError(txtNetWeight, "Chưa nhập trọng lượng NW!")
        Else
            Try
                Dim value As Double = Double.Parse(txtNetWeight.Text)
                If value < 0 Then
                    cancel = True
                    Me.ErrorProvider1.SetError(txtNetWeight, "Trọng lượng phải >= 0")
                End If
            Catch ex As Exception
                cancel = True
                Me.ErrorProvider1.SetError(txtNetWeight, "Trọng lượng này phải là giá trị số!")
            End Try
        End If

        If cancel = True Then
            txtNetWeight.Focus()
        End If

        e.Cancel = cancel
    End Sub

#End Region

    Private Sub txtHBLNo_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtHBLNo.Validating
        Dim cancel As Boolean = False
        'Chỉ kiểm tra đối với hàng xuất, hàng nhập thì chỉ nhập theo HBL nhận được
        If _objFile.IsExport Then
            'Nếu dùng HBL thì kiểm tra chiều dài chuỗi HBL No 
            If Not chkIsMaster.Checked Then
                If txtHBLNo.Text <> "" And txtHBLNo.Text <> "MASTER" Then
                    'Lấy cảng đi
                    Dim strMessage As String = ""
                    Dim maxLen As Integer
                    Dim objPOD As tblPort
                    Try
                        objPOD = _objFile.tblFileMBLs(0).tblMBL.tblVoyage.tblPort1
                        If objPOD.tblCountry.ID_Country = 6 Or objPOD.tblCountry.ID_Country = 7 Then
                            maxLen = 12
                            If txtHBLNo.Text.Length <> maxLen Then
                                strMessage = String.Format("HBL đi {0} phải là {1} ký tự", objPOD.tblCountry.CountryName, maxLen.ToString())
                            End If
                        Else
                            maxLen = 10
                            If txtHBLNo.Text.Length <> maxLen Then
                                strMessage = String.Format("HBL đi {0} phải là {1} ký tự", objPOD.tblCountry.CountryName, maxLen.ToString())
                            End If
                        End If
                    Catch ex As Exception
                        'Nếu lỗi thì bỏ qua validating
                        strMessage = "POD chưa có để ràng buộc số ký tự"
                    End Try

                    If strMessage <> "" Then
                        Me.ErrorProvider1.SetError(txtHBLNo, strMessage)
                        cancel = True
                        txtHBLNo.Focus()
                    End If
                End If
            End If
        End If
        e.Cancel = cancel
    End Sub

    'Private Sub txtHBLNo_Validated(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtHBLNo.Validated
    '    ' If all conditions have been met, clear the ErrorProvider of errors.
    '    ErrorProvider1.SetError(txtHBLNo, "")
    'End Sub
    Private Sub txtGrossWeight_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtGrossWeight.Leave

    End Sub

    Private Sub btnDetailBooking_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDetailBooking.Click
        CModule_Sy.ToExcel_DetailBooking(_objHBL.ID_HBL)
    End Sub

    Private Sub txtMeasurement_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtMeasurement.Validating
        Dim cancel As Boolean
        If String.IsNullOrEmpty(txtMeasurement.Text) Then
            cancel = True
            Me.ErrorProvider1.SetError(txtMeasurement, "Chưa nhập CBM!")
        Else
            Try
                Dim value As Double = Double.Parse(txtMeasurement.Text)
                If value < 0 Then
                    cancel = True
                    Me.ErrorProvider1.SetError(txtMeasurement, "Trọng lượng phải >= 0")
                End If
            Catch ex As Exception
                cancel = True
                Me.ErrorProvider1.SetError(txtMeasurement, "Trọng lượng này phải là giá trị số!")
            End Try
        End If

        If cancel = True Then
            txtMeasurement.Focus()
        End If

        e.Cancel = cancel
    End Sub

    Private Sub FillNotifyParty(ByVal name As String, ByVal address As String, ByVal tel As String, ByVal fax As String)
        txtNotifyParty.Text = String.Format("{0} {1}", name, vbNewLine)
        txtNotifyParty.AppendText(String.Format("Addess: {0} {1}", address, vbNewLine))
        txtNotifyParty.AppendText(String.Format("Tel: {0} {1}", tel, vbNewLine))
        txtNotifyParty.AppendText(String.Format("Fax: {0} {1}", fax, vbNewLine))
    End Sub

    Private Sub btnChangeNP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeNP.Click
        Try
            If _objFile.ID_ForeignCompany Is Nothing Then
                Dim str As String
                If _objFile.IsExport Then
                    str = "Consignee"
                Else
                    str = "Shipper"
                End If
                MessageBox.Show(String.Format("Chưa nhập {0} ở File", str))
                Exit Sub
            End If

            If _objFile.IsExport Then 'Consignee là ForeignCompany
                'If chkIsMaster.Checked Then 'Dùng master bill thì 
                '    'Nếu chọn Consignee cho Notify Party khác với Consignee của File
                '    If cmbConsignee.SelectedValue = _objFile.ID_Agent.Value Then
                '        txtNotifyParty.Text = "SAME AS CONSIGNEE"
                '    Else 'Nếu chọn khác
                '        Dim obj As tblAgent = cmbConsignee.SelectedItem
                '        FillNotifyParty(obj.Name, obj.Address, obj.Tel, obj.Fax)
                '    End If
                'Else
                'Nếu chọn Consignee cho Notify Party khác với Consignee của File
                If cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany.Value Then
                    txtNotifyParty.Text = "SAME AS CONSIGNEE"
                Else 'Nếu chọn khác
                    Dim obj As tblForeignCompany = cmbConsignee.SelectedItem
                    FillNotifyParty(obj.Name, obj.Address, obj.Tel, obj.Fax)
                End If
                'End If
            Else 'Consignee là Company
                'If chkIsMaster.Checked Then
                '    FillNotifyParty("TAN NAM CHINH TRADING AND SERVICE CO., LTD (TANACHI CO., LTD)", _
                '                    "483/67 LE VAN SY ST., DIST 3, HOCHIMINH CITY, VIETNAM", "848-39432369 / 70", "848-38265731")
                'Else
                'Nếu chọn Consignee cho Notify Party khác với Consignee của File
                If cmbConsignee.SelectedValue = _objFile.ID_Company.Value Then
                    txtNotifyParty.Text = "SAME AS CONSIGNEE"
                Else 'Nếu chọn khác
                    Dim obj As tblCompany = cmbConsignee.SelectedItem
                    FillNotifyParty(obj.Name, obj.Address, obj.Tel, obj.Fax)
                End If
                'End If
            End If
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub

    Private Sub txtHBLNo_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtHBLNo.Validated
        'If all conditions have been met, clear the ErrorProvider of errors.
        ErrorProvider1.SetError(txtHBLNo, "")
    End Sub

    Private Sub btnCI_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        frmMain.AddNewDockContainerItem("ComercialInvoice", "Comercial Invoice Management", New ucComercialInvoice(_objHBL))
    End Sub

    Private Sub btnDefaultNotifyParty_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDefaultNotifyParty.Click
        Try
            If _objFile.ID_ForeignCompany Is Nothing Then
                Dim str As String
                If _objFile.IsExport Then
                    str = "Consignee"
                Else
                    str = "Shipper"
                End If
                MessageBox.Show(String.Format("Chưa nhập {0} ở File", str))
                Exit Sub
            End If

            If _objFile.IsExport Then
                cmbConsignee.SelectedValue = _objFile.ID_ForeignCompany.Value
            Else
                cmbConsignee.SelectedValue = _objFile.ID_Company.Value
            End If
            btnChangeNP.PerformClick()
        Catch ex As Exception
            MessageBox.Show(String.Format("{0} \n {1}", ex.Message, ex.StackTrace))
        End Try
    End Sub
    Private Sub btPrintDO_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrintDO.Click
        'lấy thông tin là HBL nào đang được chọn
        Dim hblCtrl As New CHBLController
        Dim hbl As tblHBL = Nothing
        Try
            Dim gridHBL As DevComponents.DotNetBar.Controls.DataGridViewX = _ucFileHBLGridView.DataGridView
            Dim curRowHBL As DataGridViewRow = gridHBL.CurrentRow
            Dim idHBL As Integer = CInt(curRowHBL.Cells("ID_HBL").Value)
            hbl = hblCtrl.SelectRecordByID(idHBL)
        Catch ex As Exception
            MessageBox.Show("Không chọn được HBL để in Delivery Order!")
        End Try
        If (hbl IsNot Nothing) Then
            CViewer.PrintDO(hbl)
        End If
    End Sub
    Private Sub btPrintAN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrintAN.Click
        'If (_objFile.IsExport = True) Then
        '    MessageBox.Show("Chức năng chỉ dành cho hàng nhập!")
        '    Exit Sub
        'Else
        'lấy thông tin là HBL nào đang được chọn
        Dim hblCtrl As New CHBLController
        Dim hbl As tblHBL = Nothing
        Try
            Dim gridHBL As DevComponents.DotNetBar.Controls.DataGridViewX = _ucFileHBLGridView.DataGridView
            Dim curRowHBL As DataGridViewRow = gridHBL.CurrentRow
            Dim idHBL As Integer = CInt(curRowHBL.Cells("ID_HBL").Value)
            hbl = hblCtrl.SelectRecordByID(idHBL)
        Catch ex As Exception
            MessageBox.Show("Không chọn được HBL để in Arrival Note!")
        End Try
        If (hbl IsNot Nothing) Then
            CViewer.PrintAN(hbl)
        End If
    End Sub

    Private Sub txtAmount_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmount.Leave
        Dim txtNumber As TextBox = CType(sender, TextBox)
        txtNumber.Text = TextBoxHelper.TextBoxFormatNumber(txtNumber.Text, "#,##0")
    End Sub

    Private Sub txtNetWeight_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNetWeight.Leave, txtGrossWeight.Leave
        'TextBoxHelper.TextBoxFormatNumber(sender, "#,##0.000")
        Dim txtNumber As TextBox = CType(sender, TextBox)
        txtNumber.Text = TextBoxHelper.TextBoxFormatNumber(txtNumber.Text, "#,##0.000")
    End Sub

    Private Sub txtMeasurement_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMeasurement.Leave
        'TextBoxHelper.TextBoxFormatNumber(sender, "#,##0.0000")
        Dim txtNumber As TextBox = CType(sender, TextBox)
        txtNumber.Text = TextBoxHelper.TextBoxFormatNumber(txtNumber.Text, "#,##0.0000")
    End Sub
End Class
